<template>
  <el-dialog
    v-el-drag-dialog
    :title="'欠瓶登记'"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :model="temp" label-position="right" label-width="80px">
      <el-form-item style="width: 100%;" label-width="0" prop="csmPhone">
        <el-row>
          <el-col :span="18">
            <el-input v-model.trim="searchText" placeholder="请输入" @keyup.enter.native="searchForPhone">
              <el-select slot="prepend" v-model="searchType" style="width: 100px;" placeholder="请选择">
                <el-option label="客户电话" value="csmRgPhone" />
                <el-option label="客户编号" value="csmCode" />
                <el-option label="身份证号" value="sfzh" />
              </el-select>
              <el-button slot="append" class="append-search" @click="searchForPhone">查询</el-button>
            </el-input>
          </el-col>
          <el-col :span="5" style="margin-left: 10px;">
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item style="width: 33%;" label="客户名称" prop="csmName">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item style="width: 33%;" label="联系电话" prop="csmPhone">
        <el-select v-model="submit.csmPhone" placeholder="请选择联系电话">
          <el-option v-for="(l,i) in temp.phoneItems" :key="i" :value="l.csmPhone" :label="l.csmPhone" />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 34%;" label="客户类型" prop="price">
        <el-input :value=" typeMap(temp.csmType)" disabled />
      </el-form-item>
      <el-form-item style="width: 33%;" label="责任机构" prop="orgId">
        <el-tree-select
          v-model="submitOrg.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: orgTreeData
          }"
          @node-click="selectOrgTreeChange"
        />
      </el-form-item>
      <el-form-item style="width: 67%;" label="客户地址" prop="csmAddress">
        <el-select v-model="submit.csmAddress" placeholder="请选择客户地址">
          <el-option v-for="(l,i) in temp.addressItems" :key="i" :value="l.csmAddress" :label="l.csmAddress" />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 33%;" label="商品分类" prop="address">
        <!-- <el-select v-model="temp.gtName" placeholder="请选择">
          <el-option :value="1" label="气瓶" />
        </el-select> -->
        <el-tree-select
          v-model="temp.gtId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择商品分类',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item style="width: 33%;" label="商品名称" prop="address">
        <el-select v-model="temp.goodsId" placeholder="请选择">
          <el-option v-for="(l,i) in goodsTypesDetailList" :key="i" :value="l.goodsId" :label="l.goodsName" />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 20%;" label="登记数量" prop="gdCount">
        <el-input-number v-model="temp.gdCount" label="数量" :min="1" :max="99999" controls-position="right" />
      </el-form-item>
      <el-form-item style="width: 14%;">
        <el-button type="primary" @click="addShop">添加</el-button>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :total="tableData.total"
      style="width: 100%;"
      custom-column
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button type="primary" :loading="loading" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { goodsTypeDetail, goodsTypeQueryList, queryCsmInfo, oweBottleSave, queryMap } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import goods from '../goods.json'
  import { mapGetters } from 'vuex'
  export default {
    name: 'addBottle',
    data() {
      return {
        visible: false,
        type: 'add',
        loading: false,
        selectOrgSNNo: null,
        csmTypeMap: [],
        submit: {
          csmPhone: null,
          csmAddress: null
        },
        goods: goods.data,
        goodsTreeData: [],
        goodsTypesDetailList: [],
        orgTreeData: [],
        searchType: 'csmRgPhone',
        searchText: null,
        temp: {
          gtName: 1, // 商品分类
          gdCount: 1, // 添加数量
          goodsName: null,
          select: 1,
          gtId: '',
          goodsId: ''
        },
        submitOrg: {},
        rules: {
          csmPhone: [{ required: true, message: '请输入', trigger: 'change' }],
          csmName: [{ required: true, message: '请输入用户编码', trigger: 'change' }],
          orderCode: [{ required: true, message: '请输入售保员', trigger: 'change' }],
          address: [{ required: true, message: '请选择投保地址', trigger: 'change' }],
          price: [{ required: true, message: '请输入投保金额', trigger: 'change' }]
        },

        tableData: {
          column: [
            {
              prop: 'gtName',
              label: '商品类型',
              align: 'center'
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              align: 'center'
            },
            {
              prop: 'gdCount',
              label: '登记数量',
              align: 'center'
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              render: (h, { row, $index }) => {
                return (
                  <el-link underline={false} onClick={() => this.del(row, $index)}>删除</el-link>
                )
              }
            }

          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo'
      ])
    },
    async created() {
      await this.getGoodsTreeData()
      await this.getOrgTreeData()
    },
    methods: {
      open(temp) {
        return new Promise(async resolve => {
          if (this.csmTypeMap.length === 0) {
            await this.getCsmType()
          }
          this.resolve = resolve
          this.visible = true
          this.selectOrgTreeChange(this.userInfo)
          // this.selectOrgSNNo = this.userInfo.orgSNNo
        })
      },
      // 获取客户类型
      async getCsmType() {
        const res = await queryMap({ enumName: 'CustomerType' })
        this.csmTypeMap = res.data
      },
      // 客户类型
      typeMap(value) {
        if (!value) return ''
        var obj = this.csmTypeMap.find(l => l.value === value)
        if (obj) {
          return obj.desc
        }
        return ''
      },
      async searchForPhone() {
        if (!this.searchText) return this.$message.error('查询条件不能为空')
        const params = {
          'csmStatus': 9
        }
        params[this.searchType] = this.searchText
        const res = await queryCsmInfo(params)
        if (res.data) {
          console.log('用户信息', res.data)
          console.log(this.temp)
          res.data.phoneItems = res.data.phoneItems.filter((item) => {
            return item.cpStatus === 2
          })
          this.temp = { ...this.temp, ...res.data }
          // 处理默认电话和默认地址
          this.submit.csmPhone = res.data.csmRgPhone
          this.submit.csmAddress = res.data.csmRgAddress
        }
      },
      // 获取商品分类树
      async getGoodsTreeData() {
        const res = await goodsTypeQueryList({})
        var list = [res.data.find(l => l.gtId === 192)]
        const data = list.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTreeData = getTreeData(data)
        this.temp.gtId = this.goodsTreeData[0].gtId
        if (this.goodsTreeData.length > 0) this.selectTreeChange(this.goodsTreeData[0])
      },
      // 选择商品分类
      async selectTreeChange(value) {
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 选择生效机构
      selectOrgTreeChange(value) {
        this.submitOrg = {
          orgId: value.orgId,
          orgName: value.orgName,
          orgSNNo: value.orgSNNo
        }
        // this.orgSNNo = value.orgSNNo
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
          this.temp.goodsId = this.goodsTypesDetailList[0].goodsId
          // console.log(res)
        } catch (error) {
          console.log(error)
        }
      },

      // 添加商品
      addShop() {
        var { gtId, goodsId, gdCount } = this.temp
        if (!(gtId && goodsId && gdCount)) {
          this.$message.warning('请完整商品属性')
          return
        }
        const goodsName = this.goodsTypesDetailList.find(l => l.goodsId === this.temp.goodsId).goodsName
        const index = this.tableData.data.findIndex(l => l.goodsId === this.temp.goodsId)
        const item = this.tableData.data.find(l => l.goodsId === this.temp.goodsId)
        if (item) {
          this.tableData.data.splice(index, 1, {
            ...item,
            gdCount: item.gdCount + gdCount
          })
        } else {
          const obj = {
            gdCount,
            gdStatus: 2,
            goodsId: goodsId,
            goodsName: goodsName,
            gtId: gtId,
            gtName: '气瓶',
            rowid: new Date() * 1
          }
          this.tableData.data.push(obj)
        }
      },
      // 删除商品
      del(row, index) {
        const vm = this
        vm.$confirm('是否将该商品移除列表?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.tableData.data.splice(index, 1)
            // this.$message.success('删除成功')
          })
          .catch((e) => {
            // this.$message.info('已取消删除操作')
          })
      },
      // 获取所属机构数据
      async getOrgTreeData() {
        // const res = await organizationQueryList({})
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.orgTreeData = getTreeData(data)
      },
      async success() {
        this.loading = true
        if (!this.temp.csmName) {
          this.$message.error('客户名称不能为空')
          return
        }
        if (!this.submit.csmPhone) {
          this.$message.error('请选择联系电话')
          return
        }
        if (!this.submitOrg.orgSNNo) {
          this.$message.error('请选择机构')
          return
        }
        if (!this.submit.csmAddress) {
          this.$message.error('请选择客户地址')
          return
        }
        if (!this.tableData.data.length) {
          this.$message.error('请添加要登记的商品')
          return
        }
        // 处理地址
        var obj = this.temp.addressItems.find(l => l.csmAddress === this.submit.csmAddress)
        const params = {
          csmAddress: obj.csmAddress,
          csmAddressId: obj.csmAddressId,
          csmCode: this.temp.csmCode,
          csmId: this.temp.csmId,
          csmName: this.temp.csmName,
          csmPhone: this.submit.csmPhone,
          detail: this.tableData.data,
          ...this.submitOrg
        }
        const res = await oweBottleSave(params)
        if (res.success) {
          this.visible = false
          this.resolve()
          this.$message.success('登记成功')
          this.$emit('refresh')
        }
        setTimeout(() => {
          this.loading = false
        }, 1000)
      },

      reset() {
        this.type = 'add'
        this.temp = {
          gtName: 1, // 商品分类
          gdCount: 1, // 添加数量
          goodsName: null,
          select: 1
        }
        this.selectOrgTreeChange(this.userInfo)
        // this.selectOrgSNNo = this.userInfo.orgSNNo
        if (this.goodsTypesDetailList.length > 0) this.temp.goodsId = this.goodsTypesDetailList[0].goodsId
        this.submit = {}
        this.tableData.data = []
        this.searchText = null
        this.temp.gtName = 1
        this.temp.gdCount = 1
        this.temp.goodsName = null
        this.temp.select = 1
        this.gtId = ''
        this.goodsId = ''
        this.submitOrg = {}
        this.searchType = 'csmRgPhone'
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  /deep/ .el-input-number {
    width: 100px;
    .el-input__inner {
      // padding:0;
      width: 100px;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
</style>
